import urllib
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import images
from google.appengine.api import urlfetch 
from google.appengine.api.images import crop

# quan ju bian liang
url_template = 'http://appschallenge.juzz4.com/api/snapshot?data={"sessionid":"%s","deviceid":%s}'
zoom = 0
horizontal = 1 
vertical = 1
pic_matrix = [[],[],[]]
last_pic = None
cutted = False

def cut(snapshot):
	global pic_matrix
	global cutted

	if not cutted:
		pic_matrix[0].append(crop(snapshot,0.0,0.0,0.5,0.5))
		pic_matrix[0].append(crop(snapshot,0.25,0.0,0.75,0.5))
		pic_matrix[0].append(crop(snapshot,0.5,0.0,1.0,0.5))
		pic_matrix[1].append(crop(snapshot,0.0,0.25,0.5,0.75))
		pic_matrix[1].append(crop(snapshot,0.25,0.25,0.75,0.75))
		pic_matrix[1].append(crop(snapshot,0.5,0.25,1.0,0.75))
		pic_matrix[2].append(crop(snapshot,0.0,0.5,0.5,1.0))
		pic_matrix[2].append(crop(snapshot,0.25,0.5,0.75,1.0))
		pic_matrix[2].append(crop(snapshot,0.5,0.5,1.0,1.0))
		cutted = True
	else:
		pic_matrix[0][0] = crop(snapshot,0.0,0.0,0.5,0.5)
		pic_matrix[0][1] = crop(snapshot,0.25,0.0,0.75,0.5)
		pic_matrix[0][2] = crop(snapshot,0.5,0.0,1.0,0.5)
		pic_matrix[1][0] = crop(snapshot,0.0,0.25,0.5,0.75)
		pic_matrix[1][1] = crop(snapshot,0.25,0.25,0.75,0.75)
		pic_matrix[1][2] = crop(snapshot,0.5,0.25,1.0,0.75)
		pic_matrix[2][0] = crop(snapshot,0.0,0.5,0.5,1.0)
		pic_matrix[2][1] = crop(snapshot,0.25,0.5,0.75,1.0)
		pic_matrix[2][2] = crop(snapshot,0.5,0.5,1.0,1.0)

	return None

# the pic requset handler
class Request(webapp.RequestHandler):
	def get(self):
		global last_pic
		global url_template
		global pic_matrix
		global zoom
		global horizontal
		global vertical

		# get the parameters in URL
		s_id = self.request.get("sid")
		d_id = self.request.get("did")
		width = self.request.get("width")
		height = self.request.get("height")

		url = url_template % (s_id,d_id)
		
		try:
			result = urlfetch.fetch(url)
		except urlfetch.DownloadError:
			if last_pic:
				self.response.headers['Content-Type'] = 'image/jpeg'
				self.response.out.write(last_pic)
			else:
				self.response.headers['Content-Type'] = 'text/plain'
				self.response.headers['HTTP Status'] = 401
				self.response.out.write("init overtime")
			return None

		pic = result.content
	
		if zoom == 0:
			
			#if return 200
			if result.status_code == 200:
				pic = images.Image(pic)
				pic.resize(int(width), int(height))
				pic = pic.execute_transforms(images.JPEG)
				self.response.headers['Content-Type'] = 'image/jpeg'
				self.response.out.write(pic)
				last_pic = pic

			#if return 400 or 403, it means the sid is overtime
			else:
				self.response.headers['Content-Type'] = 'text/plain'
				self.response.headers['HTTP Status'] = result.status_code
				self.response.out.write("session id overtime")
		
		else:
			cut(pic)
			last_pic = pic_matrix[horizontal][vertical]
			last_pic = images.Image(last_pic)
			last_pic.resize(int(width), int(height))
			last_pic = last_pic.execute_transforms(images.JPEG)
			self.response.headers['Content-Type'] = 'image/jpeg'
			self.response.out.write(last_pic)

# the "zoom,pan,titl handler"
class Action(webapp.RequestHandler):
	def get(self):
		
		#get the parameters in the URL
		global zoom
		global horizontal
		global vertical
		zoom = int(self.request.get("zoom"))
		horizontal = int(self.request.get("h"))
		vertical = int(self.request.get("v"))
				
		# return succeed msg
		self.response.headers['Content-Type'] = 'text/plain'
		self.response.out.write("succeed")

		return None
	
class Fetch(webapp.RequestHandler):
	def get(self):
		
		#get parameters
		width = self.request.get("width")
		height = self.request.get("height")
		url = self.request.get("url")

		url = "http://" + url

		try:
			result = urlfetch.fetch(url)
		except urlfetch.DownloadError:
			if last_pic:
				self.response.headers['Content-Type'] = 'image/jpeg'
				self.response.out.write(last_pic)
			else:
				self.response.headers['Content-Type'] = 'text/plain'
				self.response.headers['HTTP Status'] = 401
				self.response.out.write("init overtime")
			return None

		pic = result.content
	
		if zoom == 0:
			
			#if return 200
			if result.status_code == 200:
				pic = images.Image(pic)
				pic.resize(int(width), int(height))
				pic = pic.execute_transforms(images.JPEG)
				self.response.headers['Content-Type'] = 'image/jpeg'
				self.response.out.write(pic)
				last_pic = pic

			#if return 400 or 403, it means the sid is overtime
			else:
				self.response.headers['Content-Type'] = 'text/plain'
				self.response.headers['HTTP Status'] = result.status_code
				self.response.out.write("session id overtime")
		
		else:
			cut(pic)
			last_pic = pic_matrix[horizontal][vertical]
			last_pic = images.Image(last_pic)
			last_pic.resize(int(width), int(height))
			last_pic = last_pic.execute_transforms(images.JPEG)
			self.response.headers['Content-Type'] = 'image/jpeg'
			self.response.out.write(last_pic)


application = webapp.WSGIApplication(
                    [('/request', Request),
					 ('/action', Action),
					 ('/fetch',Fetch)],
                       debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
